<template>
    <div class="chat-list-panel w-full h-full flex flex-col bg-white overflow-hidden">
        <!-- Search Bar -->
        <div class="p-3 border-b border-gray-100">
            <div class="flex items-center bg-gray-100 rounded-full px-4 py-2">
                <i class="fas fa-search text-gray-400 mr-2"></i>
                <input 
                    v-model="searchText" 
                    type="text" 
                    placeholder="搜索" 
                    class="bg-transparent w-full focus:outline-none text-sm"
                >
                <button class="text-gray-500 ml-auto" @click="addNewChat">
                    <i class="fas fa-plus"></i>
                </button>
            </div>
        </div>

        <!-- Loading State -->
        <div v-if="isLoading" class="flex-1 flex items-center justify-center">
            <div class="text-gray-500">加载中...</div>
        </div>

        <!-- Error State -->
        <div v-else-if="error" class="flex-1 flex items-center justify-center">
            <div class="text-red-500">{{ error }}</div>
        </div>

        <!-- Chat List -->
        <div v-else class="flex-1 overflow-y-auto">
            <div class="flex flex-col">
                <!-- Chat Items -->
                <div 
                    v-for="(chat, index) in filteredChats" 
                    :key="index"
                    :class="[
                        'chat-item p-3 cursor-pointer',
                        chat.id === selectedChatId ? 'bg-indigo-600' : 'hover:bg-gray-50'
                    ]"
                    @click="selectChat(chat.id)"
                >
                    <div class="flex">
                        <!-- Avatar/Icon -->
                        <div :class="[
                            'flex-shrink-0 w-10 h-10 rounded-md overflow-hidden mr-3',
                            getAvatarClass(chat)
                        ]">
                            <!-- Image Avatar -->
                            <img v-if="chat.avatar" :src="chat.avatar" alt="User" class="w-full h-full object-cover">
                            
                            <!-- Icon Avatar for AI or Default -->
                            <div v-else :class="getIconContainerClass(chat)">
                                <i :class="getIconClass(chat)"></i>
                            </div>
                        </div>

                        <!-- Chat Info -->
                        <div class="flex-1 min-w-0">
                            <!-- Title and Time -->
                            <div class="flex justify-between items-start">
                                <!-- Title with Optional Icons -->
                                <div class="flex items-center">
                                    <h3 :class="[
                                        'text-sm font-medium truncate',
                                        chat.id === selectedChatId ? 'text-white' : 'text-gray-900'
                                    ]">{{ chat.title }}</h3>
                                    
                                    <!-- Lock Icon -->
                                    <i v-if="chat.isPrivate" :class="[
                                        'fas fa-lock ml-1 text-xs',
                                        chat.id === selectedChatId ? 'text-white' : 'text-gray-500'
                                    ]"></i>
                                    
                                    <!-- Online Status -->
                                    <span v-if="chat.isOnline" class="ml-1 w-2 h-2 bg-green-500 rounded-full"></span>
                                </div>
                                
                                <!-- Timestamp -->
                                <span :class="[
                                    'text-xs',
                                    chat.id === selectedChatId ? 'text-white opacity-80' : 'text-gray-500'
                                ]">{{ chat.time }}</span>
                            </div>
                            
                            <!-- Message Preview -->
                            <p :class="[
                                'text-xs mt-1 truncate',
                                chat.id === selectedChatId ? 'text-white opacity-80' : 'text-gray-500'
                            ]">{{ chat.preview }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { useRouter } from 'vue-router';
import { getChatList, getChatById, createChat, updateChat } from '../api/chat';

export default {
    name: 'ChatListPanel',
    emits: ['chat-selected', 'chat-changed'],
    setup() {
        const router = useRouter();
        return { router };
    },
    data() {
        return {
            searchText: '',
            selectedChatId: null,
            activeChat: null,
            chats: [],
            isLoading: false,
            error: null
        }
    },
    computed: {
        filteredChats() {
            if (!this.searchText) return this.chats;
            const search = this.searchText.toLowerCase();
            return this.chats.filter(chat => 
                chat.title.toLowerCase().includes(search) || 
                chat.preview.toLowerCase().includes(search)
            );
        }
    },
    async created() {
        await this.fetchChatList();
        
        // Check if we're already on a chat route
        const currentPath = this.router.currentRoute.value.path;
        const match = currentPath.match(/^\/chat\/(.+)$/);
        
        if (match && match[1]) {
            // If we're already on a chat route, select that chat
            await this.changeChat(match[1]);
        } else {
            // Otherwise select the first chat by default
            if (this.chats.length > 0) {
                await this.changeChat(this.chats[0].id);
            }
        }
    },
    methods: {
        async fetchChatList() {
            this.isLoading = true;
            this.error = null;
            try {
                this.chats = await getChatList();
            } catch (err) {
                this.error = '加载聊天列表失败';
                console.error('Error fetching chat list:', err);
            } finally {
                this.isLoading = false;
            }
        },
        
        // Public method to be called from parent components
        async setActiveChat(chatId) {
            return await this.changeChat(chatId);
        },
        
        // Public method to get the current active chat
        getActiveChat() {
            return this.activeChat;
        },
        
        // Public method to get all chats
        getAllChats() {
            return [...this.chats];
        },
        
        // Internal method for handling UI click
        async selectChat(id) {
            if (id === this.selectedChatId) return;
            await this.changeChat(id);
            this.router.push(`/chat/${id}`);
        },
        
        // Core method for changing chats
        async changeChat(chatId) {
            try {
                const foundChat = await getChatById(chatId);
                if (foundChat) {
                    this.selectedChatId = chatId;
                    this.activeChat = { ...foundChat };
                    
                    this.$emit('chat-selected', chatId);
                    this.$emit('chat-changed', this.activeChat);
                    
                    console.log(`Changed to chat: ${this.activeChat.title}`);
                    return true;
                }
                
                console.warn(`Chat with ID ${chatId} not found`);
                return false;
            } catch (err) {
                console.error('Error changing chat:', err);
                return false;
            }
        },
        
        async addNewChat() {
            try {
                const newChat = {
                    title: `新对话 ${this.chats.length + 1}`,
                    preview: '开始一个新的对话',
                    time: '刚刚',
                    type: 'default'
                };
                
                const createdChat = await createChat(newChat);
                this.chats.unshift(createdChat);
                await this.selectChat(createdChat.id);
            } catch (err) {
                console.error('Error creating new chat:', err);
                this.error = '创建新对话失败';
            }
        },
        
        async updateChat(chatId, chatData) {
            try {
                const updatedChat = await updateChat(chatId, chatData);
                const index = this.chats.findIndex(chat => chat.id === chatId);
                if (index !== -1) {
                    this.chats[index] = updatedChat;
                    if (this.selectedChatId === chatId) {
                        this.activeChat = { ...updatedChat };
                    }
                    return true;
                }
                return false;
            } catch (err) {
                console.error('Error updating chat:', err);
                return false;
            }
        },
        
        getAvatarClass(chat) {
            if (chat.avatar) return '';
            if (chat.type === 'default') return 'bg-gray-200 flex items-center justify-center';
            if (chat.type === 'ai-fire') return 'bg-white p-1';
            if (chat.type === 'ai-robot') return 'bg-blue-100 flex items-center justify-center';
            if (chat.type === 'music') return 'bg-indigo-600 flex items-center justify-center';
            return 'bg-gray-200 flex items-center justify-center';
        },
        
        getIconContainerClass(chat) {
            if (chat.type === 'ai-fire') return 'bg-blue-500 rounded-md w-full h-full flex items-center justify-center';
            return 'w-full h-full flex items-center justify-center';
        },
        
        getIconClass(chat) {
            if (chat.type === 'default') return 'fas fa-user text-gray-400';
            if (chat.type === 'ai-fire') return 'fas fa-fire text-white text-lg';
            if (chat.type === 'ai-robot') return 'fas fa-robot text-blue-500';
            if (chat.type === 'music') return 'fas fa-music text-white';
            return 'fas fa-user text-gray-400';
        },
        
        // Helper methods
        async markChatAsRead(chatId) {
            try {
                await this.updateChat(chatId, { unread: false });
                console.log(`Marked chat ${chatId} as read`);
            } catch (err) {
                console.error('Error marking chat as read:', err);
            }
        },
        
        // Helper method to generate UUID
        generateUUID() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                const r = Math.random() * 16 | 0;
                const v = c === 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    }
}
</script>

<style scoped>
/* Custom scrollbar for the chat list */
.chat-list-panel > div::-webkit-scrollbar {
    width: 4px;
}

.chat-list-panel > div::-webkit-scrollbar-track {
    background: transparent;
}

.chat-list-panel > div::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 4px;
}

.chat-item {
    transition: background-color 0.2s;
}
</style>